package asynqQueueWorker

import (
	"context"
	"errors"
	"gdshop-back-end-go/common/libs/asynqQueue"
	"gdshop-back-end-go/common/request/TaskDataReq"
	"gdshop-back-end-go/common/tools/mylog"
	"gdshop-back-end-go/service-order/OrderService"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"github.com/hibiken/asynq"
)

var orderTopicFn = map[asynqQueue.OrderTopicType]func(ctx context.Context, t *asynq.Task) error{
	asynqQueue.CloseNoPayOrder: func(ctx context.Context, t *asynq.Task) error {
		mylog.InfoLog("执行任务 - CloseNoPayOrder - 关闭未支付订单 - 开始")
		// 关闭未支付订单
		closeNoPayOrderData := TaskDataReq.CloseNoPayOrder{}
		err := gjson.DecodeTo(t.Payload(), &closeNoPayOrderData)
		if err != nil {
			glog.Async().Cat("CloseNoPayOrder").Error("解析 Payload 失败 ，error Message:",
				err.Error())
			return err
		}
		jieguo := OrderService.CloseNoPayOrderByTaskData(nil, closeNoPayOrderData)
		mylog.InfoLog("执行任务 - CloseNoPayOrder - 关闭未支付订单 - 结束 code:", jieguo.Code, " message:", jieguo.Message)
		if jieguo.Code != 0 {
			glog.Async().Cat("CloseNoPayOrder").Error("error Message:",
				jieguo.Message, " orderId:", closeNoPayOrderData.OrderId)

			return errors.New(jieguo.Message)
		} else {
			return nil
		}
	},
	asynqQueue.ConfirmOrder: func(ctx context.Context, t *asynq.Task) error {
		mylog.InfoLog("执行任务 - ConfirmOrder - 确认收货 - 开始")
		// 发货后 14 天，自动确认收货
		orderId := gconv.Int(t.Payload())
		jieguo := OrderService.CompleteOrder(nil, orderId)
		mylog.InfoLog("执行任务 - ConfirmOrder - 确认收货 - 结束 code:", jieguo.Code, " message:", jieguo.Message)
		if jieguo.Code != 0 {
			glog.Async().Cat("ConfirmOrder").Error("error Message:",
				jieguo.Message, " data:", orderId)

			return errors.New(jieguo.Message)
		} else {
			return nil
		}
	},
	asynqQueue.EvaluatedOrder: func(ctx context.Context, t *asynq.Task) error {
		// 订单完成后 7 天，自动好评
		return nil
	},
}

func InitTopic(topics ...asynqQueue.OrderTopicType) {
	srv := asynq.NewServer(
		asynqQueue.GetRedisClientOpt(),
		asynq.Config{
			Concurrency: 10, // 并发数
		},
	)
	mux := asynq.NewServeMux()
	// 注册任务
	for _, topic := range topics {
		mux.HandleFunc(asynqQueue.OrderTopicName[topic], orderTopicFn[topic])
	}
	go srv.Run(mux)
}
